﻿using Furion.DatabaseAccessor;
using System;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Microsoft.EntityFrameworkCore;

namespace BlazorOrdering.Core
{
   public class Order : Entity, IEntityTypeBuilder<Order>
    {
        [Required(ErrorMessage = "请选择用餐日期")]
        [DisplayName("用餐日期")]
        [DisplayFormat(DataFormatString = "{0:yyyy年MM月dd日 dddd}")]
        public DateTime Day { get; set; }

        [Required(ErrorMessage = "订购人必填")]
        [DisplayName("用餐人员")]
        public string UserName { get; set; }


        [Required(ErrorMessage = "合计不能为空")]
        [Range(1, 9999, ErrorMessage = "合计不能大于{2} 不能小于{1}")]
        [DisplayName("合计")]
        public double Total { get; set; } = 0;

        [Required(ErrorMessage = "是否有早餐不能为空")]
        [DisplayName("是否含早餐")]
        public bool HasBreakfast { get; set; } = false;

        [Required(ErrorMessage = "详单不能为空")]
        [DisplayName("订单明细")]
        public List<OrderStatement> OrderDetails { get; set; } = new();

        public void Calculate()
        {
            double total = 0;
            //循环开始前的状态为 false， 如果循环结束，还是 false ，说明循环过程中未找到有早餐的，
            //不管怎么样，要讲订单的状态设置为没有早餐。
            bool haveb = false;
            foreach (OrderStatement item in OrderDetails)
            {
                total = total + item.subtotal;
                if (item.Type=="早餐")
                {
                    HasBreakfast = true;
                    haveb = true;
                }
            }
            if (!haveb)
            {
                //如果在上述循环中没有发现早餐，则将标志设置为否。
                HasBreakfast = false;
            }
            this.Total = total;
        }

        public void Configure(EntityTypeBuilder<Order> entityBuilder, DbContext dbContext, Type dbContextLocator)
        {
            entityBuilder.HasKey(u => u.Id);//将单个属性配置为实体的主键
            entityBuilder.Property(b => b.CreatedTime).HasDefaultValueSql("getdate()");
            //https://docs.microsoft.com/zh-cn/ef/core/modeling/relationships?tabs=fluent-api%2Cfluent-api-simple-key%2Csimple-key
            //modelBuilder.Entity<Blog>().HasMany(b => b.Posts).WithOne();
            entityBuilder.HasMany(s => s.OrderDetails).WithOne().OnDelete(DeleteBehavior.Cascade); 
            //创建导航属性后，你可能需要对其进行进一步配置。
            entityBuilder.Navigation(b => b.OrderDetails).UsePropertyAccessMode(PropertyAccessMode.Property);

        }
    }
}
